/*
 * Copyright 2020-2030 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.gitee.minimalismstyle.fresh.oss.controller

import com.gitee.minimalismstyle.fresh.common.core.exception.MessageException
import com.gitee.minimalismstyle.fresh.common.core.extra.log
import com.gitee.minimalismstyle.fresh.common.security.util.SecurityContextUtils
import com.gitee.minimalismstyle.fresh.oss.api.model.OssFile
import com.gitee.minimalismstyle.fresh.oss.api.service.OssFileService
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import org.springframework.web.bind.annotation.*
import java.io.IOException
import java.net.URLEncoder
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * 文件管理rest
 * @author maoxiaodong
 */
@Api(value = "oss/file", tags = ["文件管理"])
@RestController
@RequestMapping("oss/file")
class OssFileController(val ossFileService: OssFileService) {

    @ApiOperation("下载文件")
    @GetMapping("download/{id}")
    fun download(@PathVariable("id") id: Long, request: HttpServletRequest, response: HttpServletResponse) {
        val ossFile = ossFileService.findById(id).get()
        download(ossFile, request, response)
    }

    @ApiOperation("下载并删除临时文件")
    @GetMapping("download/temp/{id}")
    fun downloadTemp(@PathVariable("id") id: Long, request: HttpServletRequest, response: HttpServletResponse) {
        val ossFile = ossFileService.findById(id).get()
        download(ossFile, request, response)
        if(ossFile.createdBy == SecurityContextUtils.user().id){
            ossFileService.deleteById(ossFile.id!!)
        }else{
            throw MessageException(message = "没有权限")
        }
    }

    private fun download(ossFile: OssFile, request: HttpServletRequest, response: HttpServletResponse){
        try {
            response.outputStream.use { os ->
                response.characterEncoding = "utf-8"
                response.contentType = "application/octet-stream;charset=UTF-8"
                response.setContentLength(ossFile.size!!.toInt())
                val encodedFileName = URLEncoder.encode(ossFile.name, "UTF8")
                var contentDisposition = String.format("attachment;fileName=\"%s\"", encodedFileName)
                var userAgent = request.getHeader("User-Agent")
                if (userAgent != null) {
                    userAgent = userAgent.toLowerCase()
                    if (userAgent.indexOf("firefox") != -1) {
                        contentDisposition = String.format("attachment;fileName*=UTF-8''%s", encodedFileName)
                    }
                }
                response.setHeader("Content-Disposition", contentDisposition)
                ossFileService.read(ossFile.id!!, os)
            }
        } catch (e: IOException) {
            log.error(e.message, e)
        }
    }
}